package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.Category;
import entities.Link;

import admin.forms.LinkForm;
import admin.models.CategoryModel;
import admin.models.LinkModel;

@SuppressWarnings("serial")
public class LinkAddServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {

		TreeMap<String, String> check = new TreeMap<String, String>();
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories =  categoryModel.getAll();
		
		Link link = new Link();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("link", link);
		request.setAttribute("categories", categories);
		try {
			request.getRequestDispatcher("/admin/pages/link_form.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories =  categoryModel.getAll();
		
		LinkModel linkModel = LinkModel.getInstance();
		Link link = new Link();
		
		TreeMap<String, Object> form = (TreeMap<String, Object>) LinkForm.checkValid(request, link);
		link = (Link) form.get("link");
		check = (TreeMap<String, String>) form.get("checkValid");
		
		if (check.size() == 0) {
			link.setAuthKey(IdUniqueHelper.getId());
			linkModel.insert(link);

			request.setAttribute("success", "Add success link " + link.getId());
			link = new Link();
			link.setId(IdUniqueHelper.getId());
		}
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("link", link);
		request.setAttribute("categories", categories);
		try {
			request.getRequestDispatcher("/admin/pages/link_form.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
